package fr.cephb.berkeleydb.binding;

import java.util.HashMap;
import java.util.Map;


import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;

/** simple serialization object
 * Pierre Lindenbaum
 * Copied from my personnal library http://code.google.com/p/lindenb/source/browse/trunk/src/java/org/lindenb/berkeley/binding/ObjectBinding.java
 * 
 *  */
public class JSONBinding
	extends AbstractObjectBinding
	{
	public JSONBinding()
		{
		
		}
	
	@Override
	@SuppressWarnings("unchecked")
	protected Map createMap(int n)
		{
		return new HashMap<String,Object>(n);
		}
	
	@Override
	@SuppressWarnings("unchecked")
	protected Map readMap(TupleInput in)
		{
		int n=in.readInt();
		Map map= createMap(n);
		for(int i=0;i<n;++i)
			{
			map.put(
				in.readString(),	
				entryToObject(in)
				);
			}
		return map;
		}
	
	@Override
	@SuppressWarnings("unchecked")
	protected void writeMap(Object object, TupleOutput out)
		{
		out.writeByte(OP_CODE_MAP);
		Map m=(Map)object;
		out.writeInt(m.size());
		for(Object o:m.keySet())
			{
			out.writeString(String.class.cast(o));
			objectToEntry(m.get(o),out);
			}
		}
	}
